#!/usr/bin/env python3

from epics import PV, caget
import datetime
import time

class alarm(object):
    ''' Vacuum alarm
    '''
    def onVacuumChange(self, pvname=None, value=None, conn=None, host=None, timestamp=None, **kwargs):
        if self.init_status is True:
            self.value = value
            self.timestamp = timestamp
            # Vacuum status
            self.out_of_limit_check()
            if (conn is False):
            	# the place is used to generate alarm of pv losing connection
                if self.logging is None:
                    print('ca connection status changed: ', pvname, conn, host)
                else:
                    self.logging.info('ca connection status changed:  %s %s %s', pvname, conn, host)
            else: pass
        else: pass

    def out_of_limit_check(self):
        if self.value < self.threshold_mildly:
            self.out_of_limit = 0    # vacuum
        elif self.value < self.threshold_slightly:
            self.out_of_limit = 1    # vacuum_out_of_limit_mildly
            self.log_data = 'vacuum_out_of_limit_mildly.'
            self.callback_function()
        elif self.value < self.threshold_critical:
            self.out_of_limit = 2    # vacuum_out_of_limit_lightly
            self.callback_function()
            self.log_data = 'vacuum_out_of_limit_slightly.'
        else:
            self.out_of_limit = 3    # vacuum_out_of_limit_critical
            self.callback_function()
            self.log_data = 'vacuum_out_of_limit_critical.'

    def callback_function(self):
        if callable(self.callback):
            self.callback(self)
        else: pass

    # Decorator for PV
    # PV for monitor
    # Vacuum PV
    @property
    def value_now(self):
        value_temp = None
        while value_temp == None:
            time.sleep(0.2)
            value_temp = self.pv.get()
        return value_temp

    @property
    def status(self):
        return self.pvname+' = '+str(self.value_now)

    def initVacuum(self, vacuum_dict):
        self.pvname = vacuum_dict['pvname'][1]
        caget(self.pvname)
        self.pv = PV(self.pvname, callback=self.onVacuumChange)
        self.value = self.value_now
        self.timestamp = None
        self.threshold_mildly = float(vacuum_dict['threshold_mildly'])
        self.threshold_slightly = float(vacuum_dict['threshold_slightly'])
        self.threshold_critical = float(vacuum_dict['threshold_critical'])
        self.out_of_limit_check()

    def __init__(self, vacuum_dict, callback=None, logging=None, *args, **kwargs):
        self.init_status = False
        self.logging = logging
        self.callback = callback
        self.initVacuum(vacuum_dict)
        self.init_status = True

    def __del__(self):
        print('Delete vacuum.alarm instance -> '+self.pvname)

def main():
    pass

if __name__ == '__main__':
    main()
